const { exec } = require('../db')

const router = require('koa-router')()

//请求数据，分页、模糊搜素
router.get('/list', async (ctx, next) => {
  let { pageIndex, pageSize, values } = ctx.query
  let sql = `SELECT * FROM list WHERE name LIKE '%${values}%' LIMIT ${pageIndex},${pageSize}`
  let totalSql = `SELECT * FROM list WHERE name LIKE '%${values}%'`
  const data = await exec(sql)
  const total = await exec(totalSql)
  ctx.body = {
    code: 200,
    data,
    total: total.length,
    mes: 'success'
  }
})
//添加
router.post('/addlist', async (ctx, next) => {
  let { name, count, type, size, isup, ischeck } = ctx.request.body
  let sql = `INSERT INTO list (name, count, type, size, isup, id, ischeck) VALUES ('${name}', '${count}', '${type}', '${size}', ${isup}, NULL, ${ischeck});`
  const data = await exec(sql)
  ctx.body = data
  if (data.affectedRows) {
    ctx.body = {
      code: 200,
      mes: '添加成功'
    }
  } else {
    ctx.body = {
      code: 401,
      mes: '添加失败'
    }
  }
})

//删除
router.delete('/dellist', async (ctx, next) => {
  let { id } = ctx.query
  let sql = `DELETE FROM list WHERE list.id = ${id}`
  const data = await exec(sql)
  if (data.affectedRows) {
    ctx.body = {
      code: 200,
      mes: '删除成功'
    }
  } else {
    ctx.body = {
      code: 301,
      mes: '删除失败'
    }

  }
})

//修改
router.put('/editlist', async (ctx, next) => {
  const { id, isup } = ctx.request.body
  let sql = `UPDATE list SET isup = '${isup}' WHERE list.id = ${id};`
  const isEdit = await exec(sql)
  if (isEdit.affectedRows) {
    ctx.body = {
      code: 200,
      mes: '修改成功'
    }
  } else {
    ctx.body = {
      code: 301,
      mes: '修改失败'
    }

  }
})
module.exports = router
